import com.mysql.fabric.xmlrpc.base.Array;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import net.minecraft.server.v1_16_R3.Block;
import net.minecraft.server.v1_16_R3.NBTTagCompound;
import net.minecraft.server.v1_16_R3.NBTTagInt;
import net.minecraft.server.v1_16_R3.NBTTagString;
import org.bukkit.*;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.*;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.File;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main extends JavaPlugin implements CommandExecutor, TabCompleter {

    @Override
    public void onLoad() {
        //加载配置文件
        doLoadConfig();
        //建立Redis连接
        doRedisConnect();
    }

    @Override
    public void onEnable() {
        try {
            //读取配置文件
            FileConfiguration config = getConfig();
            //绑定指令与执行器
            getCommand("/").setExecutor(this);
            getCommand("/").setTabCompleter(this);
            getCommand("rt").setExecutor(this);
            getCommand("rt").setTabCompleter(this);
            getCommand("redentreasure").setExecutor(this);
            getCommand("redentreasure").setTabCompleter(this);
            //注册监听器
            Bukkit.getPluginManager().registerEvents(new Monitor(config, this), this);
            //启用定时公告
            if (config.getBoolean("notice.enable"))
                doNoticeEnable(config);
            //启用定时清理
            if (config.getBoolean("clear.enable"))
                doClearEnable(config);
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§e插件启动成功");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4插件启动失败");
            onDisable();
        }
    }

    @Override
    public void onDisable() {
        //建立Redis连接
        RedisInstance.getInstance().disable();
        Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4插件已停止运行");
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        String command = new Order().get(args.length > 0 ? args[0] : "menu");
        if (command != null) {
            try {
                Executor.class.getMethod(command, CommandSender.class, String[].class).invoke(new Executor(), sender, args);
            } catch (Exception e) {
                Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4指令执行异常：" + cmd + " " + command);
                return false;
            }
        }
        return true;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        Order orders = new Order();
        String players = "";
        for (Player player : Bukkit.getOnlinePlayers()) {
            players = players + player.getName() + ",";
        }
        if (args.length > 1) return Arrays.asList(players.split(","));
        if (args.length == 0) return Arrays.asList(orders.getAll());
        return Arrays.stream(orders.getAll()).filter(s -> s.startsWith(args[0])).collect(Collectors.toList());
    }

    private void doDatabaseConnect() {
        try {
            DatabaseInstance.getInstance().enable();
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§eMySQL连接成功");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4MySQL连接失败");
        }
    }

    private void doRedisConnect() {
        try {
            RedisInstance.getInstance().enable();
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§eRedis连接成功");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4Redis连接失败");
        }
    }

    private void doLoadConfig() {
        try {
            if (!getDataFolder().exists()) getDataFolder().mkdir();
            if (!(new File(getDataFolder(), "config.yml").exists())) saveDefaultConfig();
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§e配置文件加载成功");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§4配置文件加载失败");
        }
    }

    private void doNoticeEnable(FileConfiguration config) {
        new BukkitRunnable() {
            private List<String> content = config.getStringList("notice.content");
            private Integer period = content.size() - 1;
            private Integer counter = 0;

            @Override
            public void run() {
                Bukkit.broadcastMessage(content.get(counter));
                counter = counter >= period ? 0 : counter + 1;
            }
        }.runTaskTimer(this, 0, config.getInt("notice.unit") * 20);
        Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§e轮播公告启用成功");
    }

    private void doClearEnable(FileConfiguration config) {
        JavaPlugin plugin = this;
        new BukkitRunnable() {
            private List<String> content = config.getStringList("clear.content");
            private Integer period = config.getInt("clear.period");
            private Integer interim = config.getInt("clear.interim");
            private Integer counter = 0;

            @Override
            public void run() {
                if (counter >= period) {
                    new BukkitRunnable() {
                        private Integer counter = 0;
                        private Integer countdown = config.getInt("clear.countdown");
                        private List<String> content = config.getStringList("clear.content");

                        @Override
                        public void run() {
                            Bukkit.broadcastMessage(content.get(1).replace("*-*", String.valueOf(countdown - counter)));
                            if (counter + 1 >= countdown) {
                                Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "kill @e[type=item]");
                                Bukkit.broadcastMessage(content.get(2));
                                this.cancel();
                            }
                            counter++;
                        }
                    }.runTaskTimer(plugin, 0, 20);
                } else if (counter % interim == 0 || period - counter == 1)
                    Bukkit.broadcastMessage(content.get(0).replace("*-*", String.valueOf(period - counter)));
                counter = counter >= period ? 0 : counter + 1;
            }
        }.runTaskTimer(plugin, 0, config.getInt("clear.unit") * 20);
        Bukkit.getConsoleSender().sendMessage("§f[§aRedenTreasure§f]§e定时清理启用成功");
    }

}